import { useAppSelector } from "@/store/hooks";
import { Layout, Menu } from "antd";
import { MenuInfo } from "rc-menu/lib/interface";
import { useLocation, useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { genMenuOpenKeys } from "@/utils";
import { useState } from "react";

const BasicLayoutSider = () => {
  const collapsed = useAppSelector((state) => state.app.collapsed);
  const menuItems = useSelector((state: RootState) => state.user.menuItems);
  const navigate = useNavigate();

  console.log(menuItems, "menuItems");

  const location = useLocation();
  const defaultSelectedKeys = [location.pathname];

  function handleClick(info: MenuInfo) {
    // 这里的 key 就是我们要跳转的路径
    const { key } = info;
    // 跳转
    navigate(key);
  }

  /**
   * 当 展开关闭触发
   * rootSubmenuKeys ['/about', '/dashboard', '/account']
   */
  const [openKeys, setOpenKeys] = useState<string[]>(
    genMenuOpenKeys(location.pathname)
  );
  const rootSubmenuKeys = menuItems.map((item: any) => item.key);
  function handleOpenChange(keys: string[]) {
    // 当前点击的菜单项目的key
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
      // 当前点击的菜单项目不是一个根菜单
      setOpenKeys(keys);
    } else {
      // 是一个根菜单
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  }

  return (
    <Layout.Sider trigger={null} collapsible collapsed={collapsed}>
      <div className="logo" />
      <Menu
        theme="dark"
        mode="inline"
        openKeys={openKeys}
        defaultSelectedKeys={defaultSelectedKeys}
        items={menuItems}
        onClick={handleClick}
        onOpenChange={handleOpenChange}
      />
    </Layout.Sider>
  );
};

export default BasicLayoutSider;
